#!/usr/bin/env python
#Boa:PyApp:main
# -*- coding: utf-8 -*-

import consultasBD
import utiles

modules = {}

def main():
    sucursal = utiles.getSucursalActiva()
    print "Leyendo tabla transferencias"
    sql = "SELECT ptc FROM transferencia WHERE idsucdestino='"+sucursal+"' "
    resultados = consultasBD.ordenCrudaDict(sql)
    stockActual = {}
    print  "Determinando ptcs transferidos y cantidades"
    for item in resultados:
        ptc = item["ptc"]
        try:
            stock = stockActual[ptc]
            stock+= 1
            stockActual[ptc] = stock
        except:
            stockActual[ptc] = 1
    print "Leyendo ptcs en tabla stock"
    sql = "SELECT ptc FROM stock WHERE sucursal='"+sucursal+"' "
    resultados = consultasBD.ordenCruda(sql)
    print "Resumiendo informacion de ptcs en tabla stock"
    misPTC = []
    for item in resultados:
        ptc = item[0]
        misPTC.append(ptc)
    print "Comprando PTCS transferidos contra los del stock"
    error = []
    print "Procesando PTC no existentes en stock actual"
    f = open("transferenciasRestaurar.txt","w")
    for item in stockActual:
        try:
            stock = stockActual[item]
        except:
            error.append(item)
            continue
        ptc = str(item)
        if not ptc in misPTC:
            cadena = "INSERT INTO stock(ptc,sucursal,stock) VALUES('%s','%s','%s');\n" % (ptc,sucursal,stock)
            f.write(cadena)
    f.close()
    if error!= []:
        print "PTC con error:",error

if __name__ == '__main__':
    main()
